package cn.wolfcode.shop.cloud.web.controller;

import cn.wolfcode.shop.cloud.config.AlipayProperties;
import cn.wolfcode.shop.cloud.domain.OrderInfo;

import cn.wolfcode.shop.cloud.service.IOrderInfoService;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

@RequestMapping("/pay")
@Controller
public class PayController {

    @Autowired
    private AlipayClient alipayConfig;
    @Autowired
    private AlipayProperties alipayProperties;
    @Autowired
    private IOrderInfoService orderInfoService;

    @RequestMapping("/payOrder")
    public void payOrder(String orderNo, HttpServletResponse response) throws AlipayApiException, IOException {
        OrderInfo orderInfo = orderInfoService.find(orderNo);
//设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayProperties.getReturn_url());
        alipayRequest.setNotifyUrl(alipayProperties.getNotify_url());

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderNo;
        //付款金额，必填
        String total_amount = orderInfo.getSeckillPrice()+"";
        //订单名称，必填
        String subject = "111";
        //商品描述，可空
        String body = "11111";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


        //请求
        String result = alipayConfig.pageExecute(alipayRequest).getBody();

        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        //输出
        out.println(result);
    }

    @RequestMapping("/return_url")
    public void return_url(@RequestParam Map params,HttpServletResponse response) throws AlipayApiException, IOException {
        System.out.println("同步回调时间"+new Date());
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipay_public_key(), alipayProperties.getCharset(), alipayProperties.getSign_type()); //调用SDK验证签名


        if(signVerified) {
            //商户订单号
//            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            String orderNo = (String) params.get("out_trade_no");
            response.sendRedirect("http://localhost/order_detail.html?orderNo="+orderNo);
        }else {
//            out.println("验签失败");
            response.sendRedirect("http://localhost/50x.html");
        }
    }

    @RequestMapping("/notify_url")
    public String notify_url(@RequestParam Map params) throws Exception {
        System.out.println("异步回调时间为"+new Date());
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipay_public_key(), alipayProperties.getCharset(), alipayProperties.getSign_type()); //调用SDK验证签名

        if(signVerified) {//验证成功
            //商户订单号
            String orderNo = (String) params.get("out_trade_no");

            //支付宝交易号
            String trade_no = (String) params.get("trade_no");

            //交易状态
            String trade_status = (String) params.get("trade_status");

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //修改订单的状态
//
                //加积分
            }
            return "success";
        }else {//验证失败
            return "fail";
        }

    }
}
